<template>
  <el-card class="box-card">
    <el-form :model="form" label-width="120px">
      <el-form-item label="图文">
        <el-upload
          v-model:file-list="fileList"
          action="#"
          list-type="picture-card"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadSectionFile"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
              <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <el-icon><zoom-in /></el-icon>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <el-icon><Download /></el-icon>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
      <div style="width: 100%;display: flex">
        <el-button type="primary" @click="onSubmit" :loading="loading">保存修改</el-button>
      </div>
    </el-form-item>
    </el-form>
    <el-dialog v-model="dialogVisible" title="图片预览">
      <div style="display: flex;justify-content: center;width: 100%;">
        <img w-full :src="dialogImageUrl" style="max-width:100% ;max-height:400px" alt="Preview Image" />
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup lang='ts'>
import { reactive,ref } from 'vue';
import type { UploadProps } from 'element-plus'
import useCurrentInstance from '@/utils/useCurrentInstance';
import OSS from 'ali-oss';

const { proxy } = useCurrentInstance()
const form = reactive({})
const dialogVisible = ref(false)
const loading = ref(false)
const dialogImageUrl = ref('')
const fileList = ref([]) as any
let client = ref() as  any
let config = reactive({
  aliyunServerURL:'',
  accessid:'',
  AccessKeySecret:'',
  expiration:'',
  SecurityToken:'',
  policyBase64:'',
  signature:''
})

// 格式及文件大小校验
const beforeAvatarUpload = (file) => {
  let isVideo = true, isfileSize = true
  console.log(file.type)
  if (['image/jpg', 'image/png', 'image/gif', 'image/jpeg'].indexOf(file.type) == -1) {
    proxy.$message.error("请上传正确的图片格式!");
    isVideo = false
  }else{
    isVideo = true
  }
  if (file.size / 1024 / 1024 > 5) {
    proxy.$message.error(`视频大小不能超过5M!`);
    isfileSize = false
  }else{
    isfileSize = true
  }
  return isVideo && isfileSize
}
const uploadSectionFile = (option) => {
  loading.value = true
  let file = option.file
  proxy.$api.uploadFile({file_type:'file'}).then(res => {
    // 定义上传文件的名字+后缀
    const aliyunilFeKey = res.result.token.Path + new Date().getTime() + Math.floor(Math.random() * 150) +'.'+file.name.split('.')[1]
    config.aliyunServerURL=`https://${res.result.token.Bucket}.${res.result.token.Region}.aliyuncs.com/`
    client.value = new OSS({
        accessKeyId: res.result.token.AccessKeyId,
        accessKeySecret: res.result.token.AccessKeySecret,
        stsToken: res.result.token.SecurityToken,
        region: res.result.token.Region,
        bucket: res.result.token.Bucket,
        secure:true
    })
    // 调用oss上传接口
    client.value.multipartUpload(aliyunilFeKey, file, {}).then(response=>{
      if (response.res.status === 200) {
          proxy.$message({
            type:'success',
            message:'上传成功'
          })
          fileList.value[fileList.value.length-1].url = config.aliyunServerURL+aliyunilFeKey
          loading.value = false
      }else{
        proxy.$message({
          type:'error',
          message:'上传失败'
        })
        loading.value = false
      }
    }).catch(function (err) { console.error('error: ', err) })
  })
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const handleRemove: UploadProps['onRemove'] = (uploadFile?:any,uploadFiles?:any) => {
  const index = fileList.value.findIndex(item => item.uid === uploadFile.uid)
  fileList.value.splice(index, 1)
}
const handleDownload = (file) => {
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = file.url
  a.download = file.name+proxy.$moment().format('YYYY年MM月DD日')
  a.click()
  URL.revokeObjectURL(a.href)
}
const onSubmit = () => {
  let images = [] as Array<string>
  fileList.value.map(item => {
    images.push(item.url)
  })
  proxy.$api.getCompanysetGrade({images:images}).then(res => {
    if(res.code == 200){
      proxy.$message({
        type:'success',
        message:res.msg
      })
      getCompanyGetGrade()
    }
  })
}
// 获取安全生产评分表
const getCompanyGetGrade = () => {
  proxy.$api.getCompanyGetGrade().then(res => {
    let arr = [] as any
    res.result.map(item => {
      arr.push({
        name:item.substring(item.lastIndexOf('/')+1),
        url:item
      })
    })
    fileList.value = arr
  })
}
getCompanyGetGrade()
</script>

<style lang='scss' scoped>
p{
  margin: 0;
  padding: 0;
  padding-bottom: 10px;
  text-align: right;
  font-size: 14px;
}
.el-alert{
  background-color: rgba(255, 255, 255, 0) !important;
}
.avatar-uploader{
  width: 200px;
  height: 200px;
}
</style>
